//
//  BannerCell.swift
//  clreader
//
//  Created by colin on 2019/3/6.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit

extension HomeViewController {
    
    class BannerCell: UITableViewCell {
        
        static let reuseId = "BannerCell"
        static let bannerSize = CGSize(width: UIScreen.main.bounds.width, height: 130.0 * (UIScreen.main.bounds.width / 375.0))
        var adClickAction:((_ adInfo:JSONObject?)->Void)?
        
        private var contentCollectionView:UICollectionView?
        private var pageControl:YLLPageControl?
        private let itemCount = 5000
        private var adDatas:[JSONObject]?
        private var itemSize:CGSize {
            return BannerCell.bannerSize
        }
        
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            self.do {
                $0.selectionStyle = .none
                $0.backgroundColor = UIColor.clear
                $0.contentView.backgroundColor = UIColor.clear
            }
            
            let layout = HorizontalLayout { () -> CGSize in
                return self.itemSize
            }
            
            let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout).then {
                $0.isPagingEnabled = true
                $0.dataSource = self
                $0.delegate = self
                $0.showsVerticalScrollIndicator = false
                $0.showsHorizontalScrollIndicator = false
                $0.backgroundColor = UIColor.clear
                $0.decelerationRate = UIScrollView.DecelerationRate.fast
                $0.register(ADContentCell.self, forCellWithReuseIdentifier: "ADContentCell")
            }
            self.contentCollectionView = collectionView
            self.contentView.addSubview(collectionView)
            collectionView.snp.makeConstraints( { (make) in
                make.edges.equalToSuperview()
            })
            
            self.pageControl = YLLPageControl()
            contentView.addSubview(pageControl!)
            pageControl?.snp.makeConstraints( { (make) in
                make.left.equalToSuperview().offset(15.0)
                make.bottom.equalToSuperview().offset(-15.0)
                make.height.equalTo(2.0)
            })
            self.pageControl?.isHidden = true
        }
        
        func refresh(adDatas:[JSONObject]?) {
            
            self.adDatas = adDatas
            
            if let advs = self.adDatas,!advs.isEmpty {
                
                self.contentCollectionView?.reloadData()
                self.autoScrollWithSteper(5.0)
                
                let startIndex = (self.itemCount - self.itemCount % advs.count) / 2
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: { [weak self] in
                    guard let `self` = self else { return }
                    self.contentCollectionView?.contentOffset = CGPoint(x: self.itemSize.width * CGFloat(startIndex) , y: 0)
                })
                self.pageControl?.numberOfPages = advs.count
                self.pageControl?.currentPage = 0
                self.pageControl?.isHidden = false
            } else {
                self.contentCollectionView?.reloadData()
                self.pageControl?.isHidden = true
            }
        }
        
        //MARK:自动轮播
        private var timer:YLLTimer?
        func autoScrollWithSteper(_ steper:TimeInterval) {
            self.stopAutoScroll()
            self.timer = YLLTimer(time: steper).handle({[weak self] in
                self?.scrollToNextItem()
            }).resume(steper)
        }
        
        func stopAutoScroll() {
            _ = self.timer?.stop()
            self.timer = nil
        }
        
        func scrollToNextItem() {
            guard let contentCollectionView_ = self.contentCollectionView else {return}
            
            let contentOffsetX = contentCollectionView_.contentOffset.x
            let contentWidth = contentCollectionView_.collectionViewLayout.collectionViewContentSize.width
            let frameWidth = contentCollectionView_.frame.width
            
            if let itemCount = self.adDatas?.count , itemCount > 1 && contentWidth > frameWidth {
                let preIndex = round( contentOffsetX / self.itemSize.width ) //加一法
                //显示后面一页
                let nextIndex = preIndex + 1
                var targetX = CGFloat(nextIndex) * self.size.width
                
                if contentOffsetX + frameWidth == contentWidth {
                    //回到第一页
                    targetX = 0
                }
                else if targetX + frameWidth > contentWidth {
                    //显示最后一页
                    targetX = contentWidth - frameWidth
                }
                
                contentCollectionView_.setContentOffset(CGPoint(x: targetX, y: 0), animated: true)
            }
        }
        
        //MARK:清理
        deinit {
            self.stopAutoScroll()
        }
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
    }
}

//MARK:ScrollViewDelegate
extension HomeViewController.BannerCell : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //pageIndex
        let contentOffsetX = scrollView.contentOffset.x
        var index = Int(contentOffsetX / self.itemSize.width)
        if let adDatas_ = self.adDatas , adDatas_.count > 1 {
            if adDatas_.count > 1 {
                index = index % adDatas_.count
            }
        }else{
            index = 0
            scrollView.contentOffset.x = 0
        }
        self.pageControl?.currentPage = index
    }
}

//MARK: UICollectionViewDataSource
extension HomeViewController.BannerCell : UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        guard let adDatas_ = self.adDatas else {
            return 0
        }
        
        if adDatas_.count > 1 {
            return self.itemCount
        } else {
            return adDatas_.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ADContentCell", for: indexPath) as! ADContentCell
        if let adDatas_ = self.adDatas , !adDatas_.isEmpty {
            var index_ = indexPath.item
            if adDatas_.count > 1 {
                index_ = index_ % adDatas_.count
            }
            let adData = adDatas_[index_]
            cell.refresh(adData: adData, itemSize: self.itemSize)
        }
        return cell
    }
}

//MARK: UICollectionViewDelegate
extension HomeViewController.BannerCell : UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let adDatas_ = self.adDatas , !adDatas_.isEmpty {
            var index_ = indexPath.item
            if adDatas_.count > 1 {
                index_ = index_ % adDatas_.count
            }
            let adData = adDatas_[index_]
            self.adClickAction?(adData)
        }
    }
}

//MARK:ADContentCell
extension HomeViewController.BannerCell {
    private class ADContentCell : UICollectionViewCell {
        
        private lazy var imageViewPhoto = UIImageView()
        private lazy var labelSubTitle = UILabel()
        private lazy var labelTitle = UILabel()
        
        func refresh(adData:JSONObject?,itemSize:CGSize) {
            
            // 图片
            if let adv_img = adData?["adv_img"] as? String,!adv_img.isEmpty,
                let baseUrl = URL(string: Router.baseUrl) {
                let imageUrl = baseUrl.appendingPathComponent(adv_img)
                self.imageViewPhoto.kf.setImage(with: imageUrl)
            } else {
                self.imageViewPhoto.image = nil
            }

        }
        
        override init(frame:CGRect) {
            super.init(frame: frame)
            
            //图片
            self.addSubview(imageViewPhoto)
            imageViewPhoto.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            
            //                //副标题
            //                labelSubTitle.font = UIFont.thinFontOfSize(18.0)
            //                labelSubTitle.textColor = UIColor(hexString: "#ffffff")
            //                self.addSubview(labelSubTitle)
            //                labelSubTitle.snp.makeConstraints { (make) in
            //                    make.left.equalTo(labelSubTitle.superview!).offset(15.0)
            //                    make.right.equalTo(labelSubTitle.superview!).offset(-15.0)
            //                    make.bottom.equalTo(labelSubTitle.superview!).offset(-50.0)
            //                }
            //
            //                //标题
            //                labelTitle = UILabel()
            //                labelTitle.font = UIFont.thinFontOfSize(30.0)
            //                labelTitle.textColor = UIColor(hexString: "#ffffff")
            //                self.addSubview(labelTitle)
            //                labelTitle.snp.makeConstraints { (make) in
            //                    make.left.equalTo(labelTitle.superview!).offset(15.0)
            //                    make.right.equalTo(labelTitle.superview!).offset(-15.0)
            //                    make.bottom.equalTo(labelSubTitle.snp.top).offset(-5.0)
            //                }
        }
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
    }
}

//MARK: YLLPageControl
extension HomeViewController.BannerCell {
    private class YLLPageControl: UIView {
        
        private var pageHandle = [UIView]()
        
        private let normalWidth:CGFloat = 12.5
        private let currentWidth:CGFloat = 25.0
        
        var numberOfPages = 0 {
            didSet{
                for subview in self.pageHandle {
                    subview.removeFromSuperview()
                }
                
                self.pageHandle.removeAll()
                
                var preView:UIView?
                
                for index in 0 ..< self.numberOfPages {
                    let pageView = UIView()
                    pageView.backgroundColor = UIColor(hex: "f2f4f5")
                    pageView.alpha = 0.5
                    pageView.layer.cornerRadius = 1.0
                    pageView.layer.masksToBounds = true
                    addSubview(pageView)
                    pageView.snp.makeConstraints( { (make) in
                        
                        if let preView_ = preView {
                            make.left.equalTo(preView_.snp.right).offset(2.0)
                        }
                        else {
                            make.left.equalTo(pageView.superview!)
                        }
                        
                        make.top.bottom.equalTo(pageView.superview!)
                        make.width.equalTo(self.normalWidth)
                        if index == numberOfPages - 1 {
                            make.right.equalTo(pageView.superview!)
                        }
                    })
                    preView = pageView
                    self.pageHandle.append(pageView)
                }
            }
        }
        
        var currentPage = 0 {
            didSet{
                var currentIndex = self.currentPage < 0 ? 0 : self.currentPage
                currentIndex = currentIndex > self.pageHandle.count - 1 ? self.pageHandle.count - 1 : currentIndex
                
                let currentPageView = self.pageHandle[currentIndex]
                currentPageView.alpha = 1
                currentPageView.snp.updateConstraints { (make) in
                    make.width.equalTo(self.currentWidth)
                }
                
                if self.pageHandle.count > oldValue {
                    let oldPageView = self.pageHandle[oldValue]
                    if currentIndex != oldValue {
                        oldPageView.alpha = 0.5
                        oldPageView.snp.updateConstraints( { (make) in
                            make.width.equalTo(self.normalWidth)
                        })
                    }
                }
            }
        }
    }
}
